import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Article } from 'src/entities/article.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private articleRepository: Repository<Article>,
  ) {}

  async findAll(findOption={}): Promise<Article[]> {
    const articles=await this.articleRepository.find(findOption);
    return articles;
  }

  async findOne(id: number): Promise<Article> {
    return await this.articleRepository.findOne(id);
  }

  async removeOne(id: number): Promise<Article> {
    const old=await this.findOne(id);
    const res=await this.articleRepository.delete(id);
    return res.affected===1?old:null;
  }

  async addOne(article: Article): Promise<Article> {
    const u=Object.assign(new Article(),article);
    u.create_time=new Date();
    const res=await this.articleRepository.insert(u);
    return this.findOne(res.identifiers[0].id);
  }

  async modifyOne(id: number,article: Article): Promise<Article> {
    const u=Object.assign(new Article(),article);
    u.update_time=new Date();
    const res=await this.articleRepository.update(id,u);
    return await this.findOne(id);
  }

  async count(option={}): Promise<number> {
    return await this.articleRepository.count(option);
  }

  async getPagination(page={},sort={},where={}){
    const p=Object.assign({
      size:10,
      current:0,
      total:0,
    },page);
    const articles=await this.findAll({
      order:sort,
      take:p.size,
      skip:p.current,
      where:where
    });
    const total = await this.count(where);
    p.total=total;
    return {
      page:p,
      articles:articles,
    }
  }
}
